package com.ls.hnks.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.hnks.common.constant.RoleConstant;
import com.ls.hnks.util.Result;
import com.ls.hnks.util.ResultCodeEnum;
import com.ls.hnks.common.constant.ScheduleRemindStatusConstant;
import com.ls.hnks.common.constant.ScheduleRemindTypeConstant;
import com.ls.hnks.model.*;
import com.ls.hnks.model.vo.ScheduleCountVo;
import com.ls.hnks.model.vo.ScheduleDetailsVo;
import com.ls.hnks.service.*;
import com.ls.hnks.mapper.ScheduleMapper;
import com.ls.hnks.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 15375
* @description 针对表【tb_schedule(日程)】的数据库操作Service实现
* @createDate 2023-01-25 21:58:11
*/
@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper, Schedule>
    implements ScheduleService{

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private SchedulePicService schedulePicService;

    @Autowired
    private CustomerService  customerService;

    @Autowired
    private ScheduleRemindService scheduleRemindService;


    @Override
    public Result getListByCustomerAndDate(String customerId,String date) {
        List<Schedule> list = scheduleMapper.getAllByCustomerAndDate(customerId,date);
        return Result.ok(list);
    }

    @Override
    public Result getListByUserAndDate(String userId,String date) {
        List<Schedule> list = scheduleMapper.getAllByUserAndDate(userId,date);
        return Result.ok(list);
    }

    @Override
    public Result getListByDate(String date) {
        List<Schedule> list = scheduleMapper.getAllByUserAndDate(null, date);
        return Result.ok(list);
    }

    @Override
    public Result countSchedule(String groupId) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.select("id");
        userQueryWrapper.eq("groupId",groupId);
        List<User> users = userService.list(userQueryWrapper);
        List<Integer> ids = users.stream().map(User::getId).collect(Collectors.toList());
        List<ScheduleCountVo> scheduleCountVoList = scheduleMapper.countSchedule(ids);
        return Result.ok(scheduleCountVoList);
    }

    @Transactional
    @Override
    public Result saveSchedule(Schedule schedule) {
        int createUserId = Integer.parseInt(StpUtil.getLoginId().toString());
        User byId = userService.getById(createUserId);
        if(byId.getRight() != RoleConstant.ADMIN && schedule.getExecutorid() != createUserId){
            return Result.fail().message("非管理员用户无法指定执行人");
        }
        schedule.setCreateuserid(createUserId);
        this.save(schedule);
        List<SchedulePic> schedulePicList = schedule.getSchedulePicList();
        if (schedulePicList != null && schedulePicList.size() > 0) {
            for (SchedulePic schedulePic : schedulePicList) {
                schedulePic.setScheduleid(schedule.getId());
                schedulePic.setCreateuserid(createUserId);
            }
            schedulePicService.saveBatch(schedulePicList);
        }

        if(schedule.getRemindtype() != ScheduleRemindTypeConstant.NOT_REMIND){
            ScheduleRemind scheduleRemind = new ScheduleRemind();
            scheduleRemind.setScheduleid(schedule.getId());
            User user = userService.getById(schedule.getExecutorid());
            scheduleRemind.setPhone(user.getPhone());
            int minutes = 0;
            if(schedule.getRemindtype() == ScheduleRemindTypeConstant.FIFTEEN_MINUTES){
                minutes = 15;
            }else if (schedule.getRemindtype() == ScheduleRemindTypeConstant.THIRTY_MINUTES){
                minutes = 30;
            }
            else if (schedule.getRemindtype() == ScheduleRemindTypeConstant.ONE_HOUR){
                minutes = 60;
            }
            else if (schedule.getRemindtype() == ScheduleRemindTypeConstant.SIX_HOUR){
                minutes = 60*6;
            }
            else if (schedule.getRemindtype() == ScheduleRemindTypeConstant.ONE_DAY){
                minutes = 60*24;
            }
            // 减去15分钟
            Date sendTime = DateUtil.subtractMinutesFromDate(schedule.getStarttime(),minutes);
            scheduleRemind.setSendtime(sendTime);
            scheduleRemind.setStatus(ScheduleRemindStatusConstant.NOT_SENT);
            scheduleRemindService.save(scheduleRemind);
        }
        return Result.ok();
    }

    @Override
    public Result getDetails(String id) {
        ScheduleDetailsVo detailsVo = new ScheduleDetailsVo();
        Schedule schedule = this.getById(id);
        if(schedule == null){
            return Result.error(ResultCodeEnum.SCHEDULE_NOT_FOUND);
        }
        BeanUtils.copyProperties(schedule,detailsVo);
        // 客户名
        Customer customer = customerService.getById(schedule.getCustomerid());
        if (customer == null) {
            detailsVo.setCustomerName("已注销");
        } else {
            detailsVo.setCustomerName(customer.getName());
        }
        // 执行者名称
        User user = userService.getById(schedule.getExecutorid());
        if (user == null) {
            detailsVo.setExecutorName("已注销");
        } else {
            detailsVo.setExecutorName(user.getName());
        }
        // 附件
        QueryWrapper<SchedulePic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scheduleid",id);
        List<SchedulePic> schedulePics = schedulePicService.list(queryWrapper);
        detailsVo.setSchedulePicList(schedulePics);
        return Result.ok(detailsVo);
    }

    @Override
    public Result getListByCustomerId(String customerId, Integer pageNo, Integer size) {
        Page<Schedule> page = new Page<>(pageNo,size);
        QueryWrapper<Schedule> scheduleQueryWrapper = new QueryWrapper<>();
        scheduleQueryWrapper.eq("customerId",customerId);
        scheduleQueryWrapper.orderByDesc("StartTime","EndTime");
        IPage<Schedule> schedulePage = this.page(page, scheduleQueryWrapper);
        List<Schedule> scheduleList = schedulePage.getRecords();
        List<Integer> executorList = scheduleList.stream().map(Schedule::getExecutorid).collect(Collectors.toList());
        if(executorList.size() > 1){
            List<User> userList = userService.listByIds(executorList);
            HashMap<Integer , String > id2nameMap = userList.stream().collect(HashMap::new, (m, v) -> m.put(v.getId(), v.getName()), HashMap::putAll);
            scheduleList.forEach(item -> {
                item.setExecutorName(id2nameMap.get(item.getExecutorid()));
            });
        }
        return Result.ok(schedulePage);
    }

    @Transactional
    @Override
    public Result removeSchedule(String id) {
//        // 删除附件
//        QueryWrapper<SchedulePic> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("scheduleID",id);
//        schedulePicService.remove(queryWrapper);
//
//        // 取消提醒
//        QueryWrapper<ScheduleRemind> remindQueryWrapper = new QueryWrapper<>();
//        remindQueryWrapper.eq("scheduleID",id);
//        ScheduleRemind scheduleRemind = scheduleRemindService.getOne(remindQueryWrapper);
//        if(scheduleRemind != null && scheduleRemind.getStatus() == ScheduleRemindStatusConstant.NOT_SENT){
//            scheduleRemind.setStatus(ScheduleRemindStatusConstant.CANCEL);
//            scheduleRemindService.updateById(scheduleRemind);
//        }

        this.removeById(id);
        return Result.ok();
    }
}




